package com.fulin.leetcode;

/**
 * @Description 删除二叉搜索树中的指定节点
 * @Author fulin
 * @Date 2022/6/2 11:10
 **/
public class Num450 {
    public TreeNode deleteNode(TreeNode root, int key) {
        if(root == null){
            return null;
        }else if(root.val > key){
            root.left = deleteNode(root.left,key);
            return root;
        }else if(root.val < key){
            root.right = deleteNode(root.right,key);
            return root;
        }else{
            //需要删除当前节点
            TreeNode left = root.left;
            TreeNode right = root.right;
            if(left == null){
                return right;
            }else if(right == null){
                return left;
            }else{
                //左右子树都不为空
                //将右树最小的节点拿出来
                TreeNode minNode = right;
                while(minNode.left != null){
                    minNode = minNode.left;
                }

                root.right = deleteNode(root.right,minNode.val);
                minNode.left = left;
                minNode.right = root.right;
                return minNode;
            }
        }
    }
}

class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode() {}
     TreeNode(int val) { this.val = val; }
     TreeNode(int val, TreeNode left, TreeNode right) {
         this.val = val;
         this.left = left;
         this.right = right;
     }
 }

